package service

import (
	"fmt"
	"ksd-social-api/commons/tools"
	"ksd-social-api/modules/special/model/vo"
	"ksd-social-api/utils/rdb"
)

type SpecialCategoryService struct{}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  查询所有的发布的和未删除的课程分类信息
 */
func (service *SpecialCategoryService) FindCategories(systemId uint64) ([]*vo.SpecialCategoryVo, error) {
	cacheKey := fmt.Sprintf("SYSTEM:SPECIAL:FindCategories:%d", systemId)
	jsonString, _ := rdb.RdbGet(cacheKey)
	var specialVos []*vo.SpecialCategoryVo
	tools.JsontoStruct(jsonString, &specialVos)
	if len(specialVos) == 0 {
		categoryList, err := specialCategoryMapper.FindCategories(systemId)
		for _, category := range categoryList {
			specialVo := vo.SpecialCategoryVo{category.Id, category.Title, category.Icon, category.ParentId, []*vo.SpecialCategoryVo{}}
			specialVos = append(specialVos, &specialVo)
		}
		return service.Tree(specialVos, 0), err
	}
	return service.Tree(specialVos, 0), nil
}

/**
*   开始把数据进行编排--递归
*   Tree(all,0)
 */
func (service *SpecialCategoryService) Tree(allList []*vo.SpecialCategoryVo, parentId uint64) []*vo.SpecialCategoryVo {
	var nodes []*vo.SpecialCategoryVo
	for _, dbMenu := range allList {
		if dbMenu.ParentId == parentId {
			childrensMenu := service.Tree(allList, dbMenu.Id)
			if len(childrensMenu) > 0 {
				dbMenu.Children = append(dbMenu.Children, childrensMenu...)
			}
			nodes = append(nodes, dbMenu)
		}
	}
	return nodes
}
